/**
 * Copyright(c) kyle.
 */
package sample.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;

/**
 * 动态添加队列
 *
 * @author kyle
 * @version 1.00.00
 * @since: [2020-09-30 10:55]
 * @updateUser: [Kyle]
 * @updateRemark: [说明本次修改内容]
 * @date: [2020-09-30 10:55]
 */
@Configuration
public class RabbitDynamicConfig implements BeanDefinitionRegistryPostProcessor {

    Binding binding(Queue queue, String key,
                    DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(key);
    }

    public Queue createQueue(String queueName) {
        return QueueBuilder.nonDurable(queueName).autoDelete().build();
    }

    @Override
    public void postProcessBeanDefinitionRegistry(final BeanDefinitionRegistry registry) throws BeansException {
        //注册监听器
        ArrayList<String> sb = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            sb.add("qqqqq" + i);
        }

        BeanDefinitionBuilder definitionBuilder =
                BeanDefinitionBuilder.genericBeanDefinition(RabbitDynamicReceiver.class);
        definitionBuilder.addPropertyValue("dynamicQueues", sb);
        registry.registerBeanDefinition("rabbitDynamicReceiver", definitionBuilder.getBeanDefinition());
    }

    @Override
    public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) throws BeansException {
        //注册交换器
        DirectExchange exchange = ExchangeBuilder.directExchange("qqqqqDirect").autoDelete().build();
        beanFactory.registerSingleton("qqqqqDirect", exchange);

        for (int i = 0; i < 100; i++) {
            //注册队列
            String queueName = "qqqqq" + i;
            Queue queue = createQueue(queueName);
            beanFactory.registerSingleton(queueName, queue);

            //注册绑定
            String bingingKey = "eeeee" + i;
            Binding binding = binding(queue, bingingKey, exchange);
            beanFactory.registerSingleton(bingingKey, binding);
        }

    }
}
